<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class controller_index extends lib_controller
{
	public function index()
	{
		$_session_ = lib_session::init();
		$islogin = $_session_->getSession('login');
		if($islogin)
		{
			@header("Location:index.php?_m=job&_a=myJobPage");
		}
		else
		{
			$this->_layout = 'login';
			return 'login';
		}
	}
	
	public function dologin()
	{
		$_xml_ = lib_xml::init();
		$prefix = $_xml_->getConfig('data/prefix');
		$current_time = time();
		$ip = $_SERVER['REMOTE_ADDR'];
		$_session_ = lib_session::init();
		$islogin = $_session_->getSession('login');
		
		if($islogin)
		{
			$this->_layout = 'init';
			return 'index';
		}
		else
		{
			$_mysql_ = lib_database::init();
			$password = sha1($_POST['password']);
			$result = $_mysql_->find('users',"u_name = '{$_POST['name']}' AND u_password = '{$password}'");
			if(!empty($result))//login successfully
			{
				if($result['u_active'] == 0) 
				{
					$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('login',$current_time,'$ip','login failure,This user is unactive','{$result['u_name']}')");
					$this->_layout = 'login';
					return 'login';
				}
				$_session_->setSession(array('ip' => $_SERVER['REMOTE_ADDR'],'login' => true,'u_role' => $result['u_role'],'u_id' => $result['u_id'],'u_name' => $result['u_name']));
				
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('login',$current_time,'$ip','login success','{$result['u_name']}')");
				@header("Location: index.php?_m=job&_a=myJobPage");
				die;
			}
			else//login failed
			{
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('login',$current_time,'$ip','login failure','unknown')");
				$this->_layout = 'login';
				return 'login';
			}
		}
	}
	
	public function dologout()
	{
		$_xml_ = lib_xml::init();
		$prefix = $_xml_->getConfig('data/prefix');
		
		
		$_session_ = lib_session::init();
		$u_name = $_session_->getSession('u_name');
		$current_time = time(); 
		$ip = $_SERVER['REMOTE_ADDR'];
		
		$_mysql_ = lib_database::init();
		//sql语句最好不要在业务逻辑中体现，这样不便于换数据库或扩充数据库，应放在数据库操作层待改进
		$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('logout',$current_time,'$ip','logout success','$u_name')");
		$_session_ = lib_session::init();
		$_session_->destorySession();
		@header("Location: index.php");
		die;
	}
}
?>